﻿using MediatR;
using RBAC.ApiWrites.Applocation.Command;
using RBAC.Domain.RbacEntity;
using RBAC.Infrasturcture.Interfaces;
using RBAC.ResultCode;
using System.Transactions;
namespace RBAC.ApiWrites.Applocation.Commandhandler
{
    public class AddRoleCommandhandler : IRequestHandler<AddRoleCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Role> rolerepository;
        private readonly IBaseRepository<RolePermission> rolepermissionrepository;
        private readonly ILogger<AddRoleCommandhandler> logger;

        public AddRoleCommandhandler(IBaseRepository<Role> rolerepository,IBaseRepository<RolePermission> rolepermissionrepository,ILogger<AddRoleCommandhandler> logger)
        {
            this.rolerepository = rolerepository;
            this.rolepermissionrepository = rolepermissionrepository;
            this.logger = logger;
        }
        public async Task<ApiResult<int>> Handle(AddRoleCommand request, CancellationToken cancellationToken)
        {
            using (var tran = rolerepository.DB.Database.BeginTransaction()) 
            {

                try
                {
                    logger.LogInformation("日志信息");


                    #region 添加角色
                    var role=new Role();
                    role.RoleName = request.RoleName;
                    role.CreateTime = DateTime.Now;
                    role.Status = 1;
                   var res= await rolerepository.AddAsync(role);
                    #endregion
                    #region 用户角色中间表添加
                    List<RolePermission> rolePermissions = new List<RolePermission>();
                    foreach (var item in request.PermissionId)
                    {
                        rolePermissions.Add(new RolePermission()
                        {
                            RoleId = role.RoleId,
                            PermissionId = item
                        });
                    }



                    await rolepermissionrepository.AddRange(rolePermissions);
                    #endregion
                    tran.Commit();
                    return new ApiResult<int>
                    {
                         Code=ApiResultEnum.新增成功,
                         Message=ApiResultEnum.新增成功.ToString(),
                          Data=res
                    };


               

                }
                catch (Exception ex)
                {
                    logger.LogError("新增角色失败=>" + ex.Message);

                    tran.Rollback();
     


                    throw;
                  
                }


            }
        }
    }
}
